/*   
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.   
 *   
 * This software is the confidential and proprietary information of   
 * DMGIS. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with DMGIS.   
 *   
 */
package com.dmgis.qxfw.dataservice.businessservice.common.util;

import java.io.File;
import java.lang.reflect.Field;
import java.util.Arrays;

public class JinUtil {

	/**
	 * Sets the java library path to the specified path
	 *
	 * @param path
	 *            the new library path
	 * @throws Exception
	 */
	public static void setLibraryPath(String path) throws Exception {
		path = CheckFileExist(path);
		System.setProperty("java.library.path", path);
		// set sys_paths to null
		final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
		sysPathsField.setAccessible(true);
		sysPathsField.set(null, null);
	}

	/**
	 * Adds the specified path to the java library path
	 *
	 * @param pathToAdd
	 *            the path to add
	 * @throws Exception
	 */
	public static void addLibraryPath(String pathToAdd) throws Exception {
		pathToAdd = CheckFileExist(pathToAdd);
		final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
		usrPathsField.setAccessible(true);
		// get array of paths
		final String[] paths = (String[]) usrPathsField.get(null);
		// check if the path to add is already present
		for (String path : paths) {
			if (path.equals(pathToAdd)) {
				return;
			}
		}
		// add the new path
		final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
		newPaths[newPaths.length - 1] = pathToAdd;
		usrPathsField.set(null, newPaths);
	}

	private static String CheckFileExist(String path) {
		if (!new File(path).isDirectory()) {
			path = path.replaceFirst("D", "E");
		}
		if (!new File(path).isDirectory()) {
			path = path.replaceFirst("E", "F");
		}
		if (!new File(path).isDirectory()) {
			path = path.replaceFirst("F", "C");
		}
		return path;
	}
}
